class Permission < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  # attr_accessible :title, :body
  validates_presence_of :level,:permission
  has_many :groups_permissions,:dependent => :destroy
  has_many :groups, :through => :groups_permissions

  def matches(actionHash, session, group, current_user)
    permissions_array = self.permission.split(",")
    
    pcontroller = self.permission.split("controller:")[1].split(",")[0]

    if actionHash[:action]
      case actionHash[:action]
      when 'index', 'show'
        return actionHash[:controller] == pcontroller
      when 'destroy', 'delete'
        return !!group.del && actionHash[:controller] == pcontroller
      end
    else
      return actionHash[:controller] == pcontroller
    end

    if actionHash[:controller] == "admin/admins" && ["edit_password","update_password"].include?(actionHash[:action])
      return current_user.id == actionHash[:id].to_i
    else

    end

    for permission_record in permissions_array
      permission = permission_record.split(":")
      begin 
        return false if actionHash[permission[0].intern].downcase != permission[1]
      rescue
        return false
      end
    end
    
    return true

  end


  def get_label
    if self.level > 0
      label = "+ "
    else
      label = "- "
    end
        
    if self.permission != ""
      label += self.permission.to_s
    else
      label += "ALL"
    end
    return label
  end

end
